package ntu.metaweb.http;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;

import ntu.metaweb.Metaweb;
import ntu.metaweb.storage.User;
import ntu.metaweb.storage.local.LocalStorageManager;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;

public class FollowContactHandler implements CommandHandler {

	@SuppressWarnings("restriction")
	@Override
	public void handleCommand(HttpExchange exchange,
			HashMap<String, String> params) throws IOException {
		
		User user = 
			LocalStorageManager.getInstance().getUserData(params.get("ownusername"));
		
		String responseMsg;
		
		if (user != null) {
			user.getTrustedUsers().add(params.get("username"));
			System.out.println(user.getTrustedUsers().toString());
			LocalStorageManager.getInstance().refreshUserData(user);
			// TODO notify the followed user first
			
			responseMsg = "<xmlresponse>\n" 
				+ "<returncode>1</returncode>\n"
				+ "<username>" + user.getName() + "</username>\n"
				+ "</xmlresponse>";
		} else {
			responseMsg = "<xmlresponse>\n" 
				+ "<returncode>0</returncode>\n"
				+ "<errormessage>You're not logged in!</errormessage>\n"
				+ "</xmlresponse>";
		}

		try {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/xml");

			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();

			responseBody.write(responseMsg.getBytes());
			responseBody.close();
			exchange.close();
			System.out.println("close follow user handler");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			exchange.close();
			System.out.println("close follow user handler");
		}
	}

}
